package com.ruoyi.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;


/**
 *  Http Client
 * @author 001955
 * @date 2013-4-24 14:08:26
 */
public class HttpsUtil {

	private static DefaultHttpClient tempClient;
	/**
	 * https client
	 * @return
	 */
	public static DefaultHttpClient getHttpsClient(){
		if(tempClient==null){
			tempClient = new DefaultHttpClient();
			tempClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,30000);
			tempClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
			enableSSL(tempClient);
			
			tempClient.getParams().setParameter("http.protocol.content-charset",
					HTTP.UTF_8);
			tempClient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			tempClient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			tempClient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,HTTP.UTF_8);
		}
		return tempClient;
	}

	/**
	 * 
	 * 
	 * @param httpclient
	 */
	private static void enableSSL(DefaultHttpClient httpclient) {
		//
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpclient.getConnectionManager().getSchemeRegistry().register(
					https);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {

		public void checkClientTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}

	};

	/**
	 * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
	 * HttpClient is an interface
	 */

	public static String sendDataByGet(String url) {
		//
		DefaultHttpClient client= getHttpsClient();
		StringBuilder urlString = new StringBuilder();
		urlString.append(url);

		String urlReq = urlString.toString();
		//
		HttpGet httpsgets = new HttpGet(urlReq);
		String strRep = "";
		try {
			HttpResponse response = client.execute(httpsgets);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				strRep = EntityUtils.toString(response.getEntity(),"UTF-8");
				// Do not need the rest
				httpsgets.abort();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strRep;
	}

	/**
	 * Send a XML-Formed string to HTTP Server by post method
	 * 
	 * @param url
	 *            the request URL string
	 * @param xmlData
	 *            XML-Formed string ,will not check whether this string is
	 *            XML-Formed or not
	 * @return the HTTP response status code ,like 200 represents OK,404 not
	 *         found
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String sendDataByPost(String url, String xmlData)
			throws Exception {
		DefaultHttpClient client= getHttpsClient();		
		HttpPost post = new HttpPost(url);	
		post.getParams().setParameter("http.protocol.content-charset",
				HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		post.getParams()
				.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

		// Construct a string entity		
//		StringEntity entity = new StringEntity(CqTool.getUTF8XMLString(xmlData),"UTF-8");
		StringEntity entity = new StringEntity(xmlData,"UTF-8");
		entity.setContentType("text/text;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		// Set XML entity
		post.setEntity(entity);
		// Set content type of request header
		post.setHeader("Content-Type", "text/text;charset=UTF-8");
		// Execute request and get the response
		HttpResponse response = client.execute(post);
		HttpEntity entityRep = response.getEntity();
		String strrep = "";
		if (entityRep != null) {
			strrep = EntityUtils.toString(response.getEntity(),"UTF-8");			
			// Do not need the rest
			post.abort();
		}
		// Response Header - StatusLine - status code
		// statusCode = response.getStatusLine().getStatusCode();
		return strrep;
	}

	

	
}